package org.example.apply.kafka;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.example.apply.entity.Apply;
import org.example.apply.entity.UserDto;
import org.example.apply.feign.MsgFeign;
import org.example.apply.feign.UserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 消息推送消费者
 */
@Slf4j
@Component
public class Consumer {

    @Autowired
    RedisTemplate redisTemplate;


    @Autowired
    MsgFeign msgFeign;

    @Autowired
    UserFeign userFeign;

    @KafkaListener(topics = {"month1011"})
    public void test(ConsumerRecord<String,String> record, Acknowledgment acknowledgment) {
        if (!redisTemplate.opsForValue().setIfAbsent(record.key(), null, 1, TimeUnit.DAYS)) {
            return;
        }
        String str = record.value();
        Apply apply = JSONUtil.toBean(str, Apply.class);
        Integer userId = apply.getUserId();

        UserDto user = userFeign.getUser(userId);
        //邮件通知
        msgFeign.send("87941125@qq.com","合同审核【"+apply.getTitle()+"】:"+apply.getReason() );
        log.info("合同审核消息消费成功");
        acknowledgment.acknowledge();
    }
}
